package com.liang.leetcode.user.controller;

import com.liang.leetcode.common.result.Result;
import com.liang.leetcode.common.result.Results;
import com.liang.leetcode.user.service.OAuthService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

/**
 * OAuth第三方登录控制器
 */
@Slf4j
@RestController
@RequestMapping("/oauth")
@RequiredArgsConstructor
public class OAuthController {

    private final OAuthService oauthService;

    /**
     * 获取授权URL
     */
    @GetMapping("/authorize/{provider}")
    public Result<Void> getAuthorizeUrl(@PathVariable("provider") String provider, HttpServletResponse response) throws IOException {
        // 获取授权URL
        String authorizeUrl = oauthService.getAuthorizeUrl(provider);
        response.sendRedirect(authorizeUrl);
        return Results.success();
    }

    /**
     * OAuth回调接口（第三方平台回调）
     */
    @GetMapping("/callback/{provider}")
    public Result<String> callback(@PathVariable("provider") String provider, @RequestParam("code") String code) {
        log.info("OAuth回调: provider={}, code={}", provider, code);
        String token = oauthService.handleCallback(provider, code);
        return Results.success("登录成功", token);
    }
}